package runze.util.io;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.XMLWriter;

/**
 * 生成xml格式文件
 * @author wrzhxy@qq.com
 * @创建时间 2017年9月1日 上午8:54:22
 */
public class XMLUtil {
	private Document document;
	private Element root;
	
	public XMLUtil() {
		getDocument();
		getSiteMapRoot();
	}
	// 初始化，生成document
	public Document getDocument() {
		document = DocumentHelper.createDocument();
		return document;
	}
	public Element getRoot(String name) {
		return document.addElement(name);
	}
	// 生成sitemap根节点
	public Element getSiteMapRoot() {
		root = document.addElement("urlset", "http://www.sitemaps.org/schemas/sitemap/0.9");
        root.addNamespace("xsi","http://www.w3.org/2001/XMLSchema-instance");
        root.addAttribute("xsi:schemaLocation","http://www.sitemaps.org/schemas/sitemap/0.9 http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd");
        
        return root;
	}
	// 根节点下的元素
	public Element createElement(String elementName) {
		return root.addElement(elementName);
	}
	// 添加元素
	public Element addElement(Element element, String elementName, String elementText) {
		return element.addElement(elementName).addText(elementText);
	}
	// 写出到文件
	public void writeXmlToFile(String path, String name) {
		XMLWriter out = null;
        try {
            // Pretty print the document to System.out
            OutputFormat format = OutputFormat.createPrettyPrint();
            out = new XMLWriter(new FileOutputStream(new File(path, name)), format);
            out.write( document );
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (out != null) {
                try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
	}
}
